/*jslint vars: true, forin: true, sloppy: true */
/*global probe, angular */
probe.controller("ProjectManagementInTeam", function ($scope, $element, ocAPI,
													   ocDialog, positionPanels) {
	var accountDI = ocDialog.queryDI($element);

	$scope.position = {};
	function getPositionData() {
		$scope.position = positionPanels.getCurrentPanelShareData();
	}

	$scope.projects = [];
	function listProjectByPosition() {
		var p = $scope.position;
		ocAPI.use('listProjectTeam').by(p.teamId, p.positionId).then(function (data) {
			$scope.projects = data.projects;
		});
	}
	$scope.projectAdd = {
		name: 'project/add',
		share: function () {
			return {
				refreshProjectList: $scope.refreshProjectList,
				position: $scope.position,
			};
		}
	};
	function deleteProjectHandle(projectId) {
		var p = $scope.position;
		ocAPI.use('deleteProject').by(projectId, p.positionId, p.teamId).then(function () {
			$scope.refreshProjectList();
		});
	}
	$scope.openProject = function (index) {
		ocDialog.getNewDI('project/detail', {
			projectId: $scope.projects[index].projectId,
			refreshProjectList: $scope.refreshProjectList,
			deleteProject: deleteProjectHandle
		}).then(function (DI) {
			DI.openDialogFrom(accountDI);
		});
	};

	$scope.refreshProjectList = function () {
		ocAPI.cache.remove('PROJECT_LIST_OF_TEAM_' + $scope.position.teamId);
		listProjectByPosition();
	};

	$scope.deleteProject = function (index, event) {
		var projectId = $scope.projects[index].projectId;
		event.stopPropagation();
		var alert = {
			title: '删除项目',
			message: '删除项目会导致项目内所有资源一并删除\n且无法恢复，您确定吗？',
			callFn: function () {
				deleteProjectHandle(projectId);
			}
		};
		ocDialog.alert(alert, accountDI);
	};

	//init
	/**
	 * To use $watch method because the 'listInTeam' controller may
	 * be instantiated in two consecutive times. So if the panel is
	 * switched, some functions in this controller must be called
	 * again.
	 */
	$scope.$watch('$parent.currentPanel', function () {
		getPositionData();
		listProjectByPosition();
		(function () {
			ocDialog.alert({
				title: '感谢您的关注',
				message: '当前团队协与权限相关功能尚未完全开发\n这里为您提供了部分功能的预览\n' +
					'我们将在下个版本修正并启用相关功能。\n\n请您继续使用个人版本功能。'
			}, accountDI);
		}());
	});
	$scope.menu = [
		{
			title: '项目(P)',
			menu: [
				{
					title: '新建项目',
					attr: 'oc-dialog-open="projectAdd"'
				}
			]
		},
		{
			title: '团队(T)',
			menu: [
				{
					title: '团队信息',
					attr: ''
				},
				null,
				{
					title: '查看当前职位',
					attr: ''
				},
				{
					title: '离职',
					attr: ''
				}
			]
		}
	];
});
